package com.yxw.springmvc.userBehavior.service.impl;

import com.yxw.springmvc.userBehavior.config.AppConfig;
import com.yxw.springmvc.userBehavior.enums.RandomCodeStatEnum;
import com.yxw.springmvc.userBehavior.mapper.RandomCodeMapper;
import com.yxw.springmvc.userBehavior.model.RandomCode;
import com.yxw.springmvc.userBehavior.service.BaseTimeService;
import com.yxw.springmvc.userBehavior.service.RandomCodeService;
import com.yxw.springmvc.userBehavior.util.RandomCodeUtils;
import com.yxw.springmvc.userBehavior.util.SequenceUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;

/**
 * Created by hp on 2016/9/23.
 */
@Service
@Slf4j
public class RandomCodeServiceImpl implements RandomCodeService{

    @Resource
    private SequenceUtil sequenceUtil;

    @Resource
    private RandomCodeMapper randomCodeMapper;

    @Resource
    private BaseTimeService baseTimeService;

    @Resource
    private AppConfig appConfig;

    @Override
    public RandomCode generate() {
        String id = sequenceUtil.getSequence();
        String passwordRandomNum = RandomCodeUtils.randomNumeric(16);
        String randomCode = id + passwordRandomNum;
        RandomCode r = new RandomCode();
        r.setId(id);
        r.setRandomCode(randomCode);
        r.setStat(RandomCodeStatEnum.NORMAL.getCode());
        r.setExpiredTime(DateUtils.addSeconds(baseTimeService.getSysdate(), appConfig.getPwdRandomCodeEffectiveSeconds()));
        randomCodeMapper.insert(r);
        return r;
    }

    @Override
    public RandomCode selectById(String id) {
        RandomCode code = randomCodeMapper.selectById(id);
        return code;
    }

    @Override
    public void update(RandomCode randomCode) {
        randomCodeMapper.update(randomCode);
    }
}
